package org.jeecg.modules.monitoring.j_monitoring.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import org.jeecg.modules.monitoring.j_monitoring.constantConfig.MonitorConstant;
import org.jeecg.modules.monitoring.j_monitoring.entity.*;
import org.jeecg.modules.monitoring.j_monitoring.mapper.EquipmentDataMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MCabinetMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlComputingResourceMapper;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MMachineRoomMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlComputingResourceService;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlNetworkResourceService;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlStorageResourcesService;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 计算资源(管理)
 * @Author: xiaoyq
 * @Date:   2023-01-08
 * @Version: V1.0
 */
@Service
public class MGlComputingResourceServiceImpl extends ServiceImpl<MGlComputingResourceMapper, MGlComputingResource> implements IMGlComputingResourceService {

    @Resource
    EquipmentDataMapper equipmentDataMapper;
    @Resource
    private MCabinetMapper cabinetMapper;
    @Resource
    private MCabinetServiceImpl cabinetService;
    @Resource
    private MMachineRoomServiceImpl roomService;
    @Resource
    private MMachineRoomMapper mMachineRoomMapper;



    @Override
    public void testImport(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MGlComputingResource> list = ExcelImportUtil.importExcel(file.getInputStream(), MGlComputingResource.class, params);
                for (MGlComputingResource resource : list){

                    if (baseMapper.selectByEquipmentNo(resource.getEquipmentNo()).size()>0){
                        continue;
                    }


                    List<EquipmentData> equipmentDataList = equipmentDataMapper.selectByCode(resource.getEquipmentNo());
                    if (equipmentDataList.size()==0){
                        continue;
                    }

                    EquipmentData data = equipmentDataList.get(0);
                    resource.setModel(data.getModel());
                    resource.setAssetNo(data.getAssetid());
                    resource.setName(data.getDevicestypename());
                    resource.setInstallDate(data.getInstalldate());
                    resource.setExpiryDateOfMaintenance(data.getEndlinedate());
                    resource.setEquipmentSerialNumber(data.getSerialnumber());
                    resource.setRemarks(data.getSpecification().toString());
                    resource.setPersonLiable(data.getUsername());
                    resource.setMachineRoomId(resource.getMachineRoom().equals("网络机房")?"1651101144400863233":"1651101078713868290");


                    List<MCabinet> cabinets = cabinetMapper.selectByName(resource.getCabinet());
                    if (cabinets.size()>0){
                        resource.setCabinetId(cabinets.get(0).getId());
                    }


                    baseMapper.insert(resource);

                }
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                e.printStackTrace();

                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean batchBindingCluster(String cluster,String clusterId, List<String> idList) {
        batchRelieveCluster(clusterId);
        UpdateWrapper<MGlComputingResource> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("cluster",cluster);
        updateWrapper.set("cluster_id",clusterId);
        updateWrapper.lambda().in(MGlComputingResource::getId,idList);
        return this.update(updateWrapper);
    }

    @Override
    public boolean batchRelieveCluster(String clusterId) {
        UpdateWrapper<MGlComputingResource> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("cluster",null);
        updateWrapper.set("cluster_id",null);
        updateWrapper.lambda().eq(MGlComputingResource::getClusterId,clusterId);
        return this.update(updateWrapper);
    }

    @Override
    public JSONObject getDeviceMapById(JSONArray nodes, JSONArray edges,int startX,int startY,String id) {
        MGlComputingResource computingResource = this.getById(id);
        JSONObject result;
        JSONObject child = new JSONObject(),edge,sChild;
        child.put("category", MonitorConstant.Computer);
        child.put("id",computingResource.getId());
        child.put("name",computingResource.getName());
        child.put("ip",computingResource.getDeviceIp());
        child.put("x",startX + MonitorConstant.StepX);
        child.put("y",startY);
        result = child;

        nodes.add(child);

        IMGlNetworkResourceService mGlNetworkResourceService = ApplicationContextUtil.getContext().getBean(IMGlNetworkResourceService.class);
        MGlNetworkResource glNetworkResource;
        int yComputer = startY,countNetwork = 0;
        IMGlStorageResourcesService storageResourcesService = ApplicationContextUtil.getContext().getBean(IMGlStorageResourcesService.class);
        //上联光纤交换机
        if(computingResource.getUplinkOpticalSwitchId()!=null && !"".equals(computingResource.getUplinkOpticalSwitchId())){
            child = new JSONObject();
            child.put("category",MonitorConstant.Network);
            child.put("id",computingResource.getUplinkOpticalSwitchId());
            child.put("name",computingResource.getUplinkOpticalSwitch());
            child.put("x",startX + MonitorConstant.StepX * 2);
            child.put("y",yComputer);
            nodes.add(child);

            edge = new JSONObject();
            edge.put("source",computingResource.getId());
            edge.put("target",computingResource.getUplinkOpticalSwitchId());
            edges.add(edge);

            //查询是否关联有存储
            MGlStorageResources storageResources = storageResourcesService.getBySwitchId(computingResource.getUplinkOpticalSwitchId());
            if(storageResources!=null){
                sChild = new JSONObject();
                sChild.put("category",MonitorConstant.Storage);
                sChild.put("id",storageResources.getId());
                sChild.put("name",storageResources.getName());
                sChild.put("ip",storageResources.getDeviceIp());
                sChild.put("x",startX + MonitorConstant.StepX * 3);
                sChild.put("y",yComputer);
                nodes.add(sChild);

                edge = new JSONObject();
                edge.put("source",computingResource.getUplinkOpticalSwitchId());
                edge.put("target",storageResources.getId());
                edges.add(edge);
            }

            yComputer += MonitorConstant.StepY;
        }
        //上联网络交换机
        if(computingResource.getOnlineNetworkSwitchId()!=null && !"".equals(computingResource.getOnlineNetworkSwitchId())) {
            glNetworkResource = mGlNetworkResourceService.getById(computingResource.getOnlineNetworkSwitchId());
            String name = glNetworkResource!=null? glNetworkResource.getName():"";
            String ip = glNetworkResource!=null? glNetworkResource.getManageIp():"";
            child = new JSONObject();
            child.put("category",MonitorConstant.Network);
            child.put("id",computingResource.getOnlineNetworkSwitchId());
            child.put("name",name);
            child.put("x",startX + MonitorConstant.StepX * 2);
            child.put("y",yComputer);
            child.put("ip",ip);
            nodes.add(child);

            edge = new JSONObject();
            edge.put("source",computingResource.getId());
            edge.put("target",computingResource.getOnlineNetworkSwitchId());
            edges.add(edge);

            yComputer += MonitorConstant.StepY;
        }

        if(computingResource.getAssociatedStorageId()!=null && !"".equals(computingResource.getAssociatedStorageId())) {
            List<String> idList = Arrays.asList(computingResource.getAssociatedStorageId().split(","));
            List<MGlStorageResources> storageResourcesList = storageResourcesService.listByIds(idList);
            if(storageResourcesList.size()>0){
                for (MGlStorageResources storageResources:storageResourcesList){
                    sChild = new JSONObject();
                    sChild.put("category",MonitorConstant.Storage);
                    sChild.put("id",storageResources.getId());
                    sChild.put("name",storageResources.getName());
                    sChild.put("ip",storageResources.getDeviceIp());
                    sChild.put("x",startX + MonitorConstant.StepX * 3);
                    sChild.put("y",yComputer);

                    nodes.add(sChild);

                    edge = new JSONObject();
                    edge.put("source",computingResource.getId());
                    edge.put("target",storageResources.getId());
                    edges.add(edge);

                    yComputer += MonitorConstant.StepY;
                }
            }
        }

        return result;
    }

    @Override
    public JSONObject getDeviceTreeById(String id) {
        MGlComputingResource computingResource = this.getById(id);
        JSONObject result;
        JSONObject child = new JSONObject();
        child.put("type","计算资源");
        child.put("id",computingResource.getId());
        child.put("name",computingResource.getName());
        child.put("ip",computingResource.getDeviceIp());
        result = child;
        JSONArray subNodes = new JSONArray();
        result.put("children",subNodes);
        JSONArray temp;
        IMGlStorageResourcesService storageResourcesService = ApplicationContextUtil.getContext().getBean(IMGlStorageResourcesService.class);
        //上联光纤交换机
        if(computingResource.getUplinkOpticalSwitchId()!=null && !"".equals(computingResource.getUplinkOpticalSwitchId())){
            child = new JSONObject();
            child.put("type","交换机");
            child.put("id",computingResource.getUplinkOpticalSwitchId());
            child.put("name",computingResource.getUplinkOpticalSwitch());
            //child.put("ip",storageResources.getDeviceIp());
            temp = new JSONArray();
            temp.add(child);
            subNodes.add(temp);

            //查询是否关联有存储
            MGlStorageResources storageResources = storageResourcesService.getBySwitchId(computingResource.getUplinkOpticalSwitchId());
            if(storageResources!=null){
                child = new JSONObject();
                child.put("type","存储");
                child.put("id",storageResources.getId());
                child.put("name",storageResources.getName());
                child.put("ip",storageResources.getDeviceIp());
                temp.add(child);
            }
        }
        IMGlNetworkResourceService mGlNetworkResourceService = ApplicationContextUtil.getContext().getBean(IMGlNetworkResourceService.class);
        MGlNetworkResource glNetworkResource;
        //上联网络交换机
        if(computingResource.getOnlineNetworkSwitchId()!=null && !"".equals(computingResource.getOnlineNetworkSwitchId())) {
            glNetworkResource = mGlNetworkResourceService.getById(computingResource.getOnlineNetworkSwitchId());
            String name = glNetworkResource!=null? glNetworkResource.getName():"";
            String ip = glNetworkResource!=null? glNetworkResource.getManageIp():"";
            child = new JSONObject();
            child.put("type","交换机");
            child.put("id",computingResource.getOnlineNetworkSwitchId());
            child.put("name",name);
            child.put("ip",ip);
            temp = new JSONArray();
            temp.add(child);
            subNodes.add(temp);
        }

        if(computingResource.getAssociatedStorageId()!=null && !"".equals(computingResource.getAssociatedStorageId())) {
            List<String> idList = Arrays.asList(computingResource.getAssociatedStorageId().split(","));
            List<MGlStorageResources> storageResourcesList = storageResourcesService.listByIds(idList);
            if(storageResourcesList.size()>0){
                for (MGlStorageResources storageResources:storageResourcesList){
                    child = new JSONObject();
                    child.put("type","存储");
                    child.put("id",storageResources.getId());
                    child.put("name",storageResources.getName());
                    child.put("ip",storageResources.getDeviceIp());
                    subNodes.add(child);
                }
            }
        }

        return result;
    }


    public String getIp(String id){
        return baseMapper.selectById(id).getDeviceIp();
    }


    public boolean saveBatch(Collection<MGlComputingResource> entityList, int size){

        //机柜列表
        List<MCabinet> cabinetList = cabinetMapper.selectAll();

        //机房列表
        List<MMachineRoom> roomList = mMachineRoomMapper.selectAll();

        //处理机房机柜id绑定问题
        for (MGlComputingResource entity : entityList){
            entity.setCabinetId(cabinetService.getId(entity.getCabinet(),cabinetList));
            entity.setMachineRoomId(roomService.getId(entity.getMachineRoom(),roomList));
        }


        String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE);
        return this.executeBatch(entityList, size, (sqlSession, entity) -> {
            sqlSession.insert(sqlStatement, entity);
        });

    }

    public MGlComputingResource selectById(String id){
        return baseMapper.selectById(id);
    }

}
